<template>
  <el-card>
    <el-form :inline="true" class="form">
      <el-form-item label="职位搜索">
        <el-input placeholder="请你输入搜索职位关键字" v-model="keyword"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="default" :disabled="keyword ? false : true" @click="search">搜索</el-button>
        <el-button type="primary" size="default" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0px;">
    <el-button type="primary" size="default" icon="Plus" @click="addRole">添加职位</el-button>
    <el-table border style="margin: 10px 0px;" :data="allRole">
      <el-table-column type="index" align="center" label="#"></el-table-column>
      <el-table-column label="ID" align="center" prop="id"></el-table-column>
      <el-table-column label="职位名称" align="center" prop="roleName" show-overflow-tooltip></el-table-column>
      <el-table-column label="创建世间" align="center" show-overflow-tooltip prop="createTime"></el-table-column>
      <el-table-column label="更新时间" align="center" show-overflow-tooltip prop="updateTime"></el-table-column>
      <el-table-column label="操作" width="280px" align="center">
        <!-- row:已有的职位对象 -->
        <template #="{ row }">
          <el-button type="primary" size="small" icon="User" @click="setPermisstion(row)">分配权限</el-button>
          <el-button type="primary" size="small" icon="Edit" @click="updateRole(row)">编辑</el-button>
          <el-popconfirm :title="`你确定要删除${row.roleName}?`" width="260px" @confirm="removeRole(row.id)">
            <template #reference>
              <el-button type="primary" size="small" icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
      :background="true" layout="prev, pager, next, jumper,->,sizes,total" :total="total" @current-change="getHasRole"
      @size-change="sizeChange" />
  </el-card>
  <!-- 添加职位与更新已有职位的结构:对话框 -->
  <el-dialog v-model="dialogVisite" :title="RoleParams.id ? '更新职位' : '添加职位'">
    <el-form :model="RoleParams" :rules="rules" ref="form">
      <el-form-item label="职位名称" prop="roleName">
        <el-input placeholder="请你输入职位名称" v-model="RoleParams.roleName"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" size="default" @click="dialogVisite = false">取消</el-button>
      <el-button type="primary" size="default" @click="save">确定</el-button>
    </template>
  </el-dialog>
  <!-- 抽屉组件:分配职位的菜单权限与按钮的权限 -->
  <el-drawer v-model="drawer">
    <template #header>
      <h4>分配菜单与按钮的权限</h4>
    </template>
    <template #default>
      <!-- 树形控件 -->
      <el-tree ref="tree" :data="menuArr" show-checkbox node-key="id" default-expand-all
        :default-checked-keys="selectArr" :props="defaultProps" />
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="handler">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import type { MenuList, MenuResponseData, Records, RoleData, RoleResponseData } from '@/api/acl/role/type'
import { reqAddOrUpdateRole, reqAllMenuList, reqAllRoleList, reqRemoveRole, reqSetPermisstion } from '@/api/acl/role'
import useLayoutStore from '@/store/modules/layout'
import { ElMessage } from 'element-plus'


let layoutStore = useLayoutStore()
let pageNo = ref(1)
let pageSize = ref(10)
let allRole = ref<Records>([])
let keyword = ref('')
let total = ref<number>(0);
//控制对话框的显示与隐藏
let dialogVisite = ref<boolean>(false);
//获取form组件实例
let form = ref<any>();
//控制抽屉显示与隐藏
let drawer = ref<boolean>(false);
//收集新增岗位数据
let RoleParams = reactive<RoleData>({
  roleName: ''
})
let menuArr = ref<MenuList>([])
let selectArr = ref([])
//树形控件的测试数据
const defaultProps = {
  children: 'children',
  label: 'name',
}
let tree = ref()

function validatorRoleName(_:any, value: any, callBack: any) {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('职位名称至少两位'))
  }
}

let rules = {
  roleName: [
    { required: true, trigger: 'blur', validator: validatorRoleName }
  ]
}

onMounted(() => {
  getHasRole()
})

async function getHasRole(pager = 1) {
  pageNo.value = pager
  let res: RoleResponseData = await reqAllRoleList(pageNo.value, pageSize.value, keyword.value)
  if (res.code === 200) {
    allRole.value = res.data.records
    total.value = res.data.total
  }
}
function search() {
  getHasRole()
  keyword.value = ''
}
function reset() {
  layoutStore.refresh = !layoutStore.refresh
}
function addRole() {
  dialogVisite.value = true
  Object.assign(RoleParams, { roleName: '', id: '' })
  nextTick(() => {
    form.value.clearValidate()
  })
}
async function setPermisstion(row: any) {
  drawer.value = true
  Object.assign(RoleParams, row)
  let res: MenuResponseData = await reqAllMenuList(RoleParams.id as number)
  if (res.code === 200) {
    menuArr.value = res.data
    selectArr.value = filterSelectMenu(menuArr.value, [])

  }
}

function filterSelectMenu(MenuList: any, initArr: any) {
  MenuList.forEach((item: any) => {
    if (item.select && item.level === 4) {
      initArr.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      filterSelectMenu(item.children, initArr)
    }
  })
  return initArr

}

async function handler() {
  const roleId = (RoleParams.id as number);
  //选中节点的ID
  let arr = tree.value.getCheckedKeys()
  //半选的ID
  let arr1 = tree.value.getHalfCheckedKeys()
  let permissionId = arr.concat(arr1)
  let res: any = await reqSetPermisstion(roleId, permissionId)
  if (res.code === 200) {
    //抽屉关闭
    drawer.value = false;
    //提示信息
    ElMessage({ type: 'success', message: '分配权限成功' });
    //页面刷新
    window.location.reload();
  }


}

//删除已有的职位
const removeRole = async (id: number) => {
    let result: any = await reqRemoveRole(id);
    if (result.code == 200) {
        //提示信息
        ElMessage({ type: 'success', message: '删除成功' });
        getHasRole(allRole.value.length > 1 ? pageNo.value : pageNo.value - 1);
    }
}

function updateRole(row: any) {
  dialogVisite.value = true
  Object.assign(RoleParams, row)
  nextTick(() => {
    form.value.clearValidate()
  })
}
function sizeChange() {
  getHasRole()
}
async function save() {
  await form.value.validate()
  let res = await reqAddOrUpdateRole(RoleParams)
  if (res.code === 200) {
    ElMessage.success(RoleParams.id ? '修改成功' : '添加角色成功')
    dialogVisite.value = false
    getHasRole(RoleParams.id ? pageNo.value : 1)
  } else {
    ElMessage.error(RoleParams.id ? '修改失败' : '添加角色失败')
  }
}


</script>

<style scoped lang="scss">
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
}
</style>
